package com.think.admin.oauth.integration.authenticator.impl;

import com.think.admin.cons.AdminCons;
import com.think.admin.oauth.exception.CustomOauth2Exception;
import com.think.admin.oauth.integration.IntegrationAuthentication;
import com.think.common.utils.SysUtils;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

/**
 * <p>
 * 图形验证码认证器
 * </p>
 *
 * @author: xwj
 * @data: 2019-05-10
 */
@Component
@RequiredArgsConstructor
public class VerificationCodeIntegrationAuthenticator extends UsernamePasswordAuthenticator {
    private final RedissonClient redissonClient;

    @Override
    public void prepare(IntegrationAuthentication integrationAuthentication) {
        // 参数提取
        String vcToken = integrationAuthentication
                .getAuthParameter(AdminCons.Oauth.VERIFICATION_CODE_AUTH_TYPE + "_token");
        String vcCode = integrationAuthentication
                .getAuthParameter(AdminCons.Oauth.VERIFICATION_CODE_AUTH_TYPE + "_code");
        if (SysUtils.isNull(vcToken, vcCode)) {
            throw new CustomOauth2Exception("必要参数为空");
        }

        // 验证码比对
        RBucket<String> bucket = redissonClient.getBucket(AdminCons.Redis.VERIFY_CODE + vcToken);
        String cacheCode = bucket.get();
        if (SysUtils.isEmpty(cacheCode) || !vcCode.toUpperCase().equals(cacheCode.toUpperCase())) {
            throw new CustomOauth2Exception("验证码错误");
        }
        bucket.delete();
        return;
    }

    @Override
    public boolean support(IntegrationAuthentication integrationAuthentication) {
        return AdminCons.Oauth.VERIFICATION_CODE_AUTH_TYPE.equals(integrationAuthentication.getAuthType());
    }
}
